# ################################################################# #
#### LOAD LIBRARY AND DEFINE CORE SETTINGS                       ####
# ################################################################# #

### Clear memory
rm(list = ls())

### Load Apollo library
library(apollo)

### Set working directory to the folder of this script
apollo_setWorkDir()

### Initialise code
apollo_initialise()

### Set core controls
apollo_control = list(
  modelDescr      = "Extended MDC with complementarity and substitution, with unobserved budget and socio-demographics",
  indivID         = "indivID",
  outputDirectory = "output"
)

# ################################################################# #
#### LOAD DATA AND APPLY ANY TRANSFORMATIONS                     ####
# ################################################################# #

### Load data from within the Apollo package
database = apollo_timeUseData

### Create consumption variables for combined activities
# outside good: time spent at home and travelling
database$t_outside = rowSums(database[,c("t_a01", "t_a06", "t_a10", "t_a11", "t_a12")]) 
database$t_leisure = rowSums(database[,c("t_a07", "t_a08", "t_a09")])

### Randomly split dataset into estimation (70%) and validation (30%)
set.seed(1)
database$validation = runif(nrow(database))>0.7
dbVal    = database[ database$validation,] # validation sample
database = database[!database$validation,] # estimation sample

# ################################################################# #
#### DEFINE MODEL PARAMETERS                                     ####
# ################################################################# #

### Parameters starting values c(name1=value1, name2=value2, ...)
apollo_beta = c(aFemale      = 0, 
                # Base utility of inside goods
                bWork        = 0, bSchool      = 0, 
                bShopping    = 0, bPrivate     = 0, 
                bLeisure     = 0, bWork_FT     = 0, 
                bWork_wknd   = 0, bSchool_young= 0, 
                bLeisure_wknd= 0, 
                # Satiation
                gWork        = 1, gSchool      = 1, 
                gShopping    = 1, gPrivate     = 1, 
                gLeisure     = 1, 
                dWorkScho    = 0, 
                # Complementarity and substitution
                dWorkShop    = 0, dWorkPriv    = 0, 
                dWorkLeis    = 0, dSchoShop    = 0, 
                dSchoPriv    = 0, dSchoLeis    = 0, 
                dShopPriv    = 0, dShopLeis    = 0, 
                dPrivLeis    = 0,
                # S.d. of error term
                sigma        = 1)

### Names of fixed parameters
apollo_fixed = c('dWorkShop', 'dWorkPriv', 'dSchoShop', 
                 'dSchoPriv', 'dSchoLeis', 'dWorkLeis')

# ################################################################# #
#### GROUP AND VALIDATE INPUTS                                   ####
# ################################################################# #

apollo_inputs = apollo_validateInputs()

# ################################################################# #
#### DEFINE MODEL AND LIKELIHOOD FUNCTION                        ####
# ################################################################# #

apollo_probabilities=function(apollo_beta, apollo_inputs, 
                              functionality="estimate"){
    
  ### Initialise
  apollo_attach(apollo_beta, apollo_inputs)
  on.exit(apollo_detach(apollo_beta, apollo_inputs))
  P = list()
  
  ### Prepare Inputs
  alts  = c("work", "school", "shopping", "private", "leisure")
  nAlt = length(alts)
  ones = setNames(as.list(rep(1, nAlt)), alts)
  continuousChoice = list(work     =     t_a02/60,
                          school   =     t_a03/60,
                          shopping =     t_a04/60,
                          private  =     t_a05/60,
                          leisure  = t_leisure/60)
  utilities = list(
    work     = bWork     + bWork_FT*occ_full_time + bWork_wknd*weekend,
    school   = bSchool   + bSchool_young*(age<=30), 
    shopping = bShopping, 
    private  = bPrivate, 
    leisure  = bLeisure  + bLeisure_wknd*weekend
  )
  gamma = list(work     = gWork,    
               school   = gSchool,
               shopping = gShopping,
               private  = gPrivate,
               leisure  = gLeisure)
  ### delta given as a list, with one entry per alternative naming the alternatives it pairs
  ### with. Each entry is differentiated on its own, so the model uses analytical gradients.
  ### Pairs not named are zero, and each pair is given once, in either direction.
  delta = list(work     = list(school   = dWorkScho, shopping = dWorkShop,
                               private  = dWorkPriv, leisure  = dWorkLeis),
               school   = list(shopping = dSchoShop, private  = dSchoPriv,
                               leisure  = dSchoLeis),
               shopping = list(private  = dShopPriv, leisure  = dShopLeis),
               private  = list(leisure  = dPrivLeis))
  emdc_settings = list(continuousChoice = continuousChoice, 
                        avail            = ones,
                        utilityOutside   = aFemale*female, 
                        utilities        = utilities, 
                        gamma            = gamma, 
                        delta            = delta, 
                        cost             = ones,
                        sigma            = sigma)
  P[["model"]] = apollo_emdc(emdc_settings, functionality)
  
  ### Comment out as necessary
  P = apollo_panelProd(P, apollo_inputs, functionality)
  P = apollo_prepareProb(P, apollo_inputs, functionality)
  return(P)
}

# ################################################################# #
#### MODEL ESTIMATION                                            ####
# ################################################################# #

model = apollo_estimate(apollo_beta, apollo_fixed, apollo_probabilities, apollo_inputs)

# ################################################################# #
#### MODEL OUTPUTS                                               ####
# ################################################################# #

# ----------------------------------------------------------------- #
#---- FORMATTED OUTPUT (TO SCREEN)                               ----
# ----------------------------------------------------------------- #

apollo_modelOutput(model)

# ----------------------------------------------------------------- #
#---- FORMATTED OUTPUT (TO FILE, using model name)               ----
# ----------------------------------------------------------------- #

apollo_saveOutput(model)

# ################################################################# #
##### POST-PROCESSING                                            ####
# ################################################################# #

### Print outputs of additional diagnostics to new output file (remember to close file writing when complete)
apollo_sink()

# ----------------------------------------------------------------- #
#---- MODEL PREDICTIONS                                          ----
# ----------------------------------------------------------------- #

model = apollo_loadModel(apollo_inputs$apollo_control$modelName)
apollo_inputs = apollo_validateInputs(database=dbVal)
pred = apollo_prediction(model, apollo_probabilities, apollo_inputs)
XObs = cbind(work      =     dbVal$t_a02/60,
              school   =     dbVal$t_a03/60,
              shopping =     dbVal$t_a04/60,
              private  =     dbVal$t_a05/60,
              leisure  = dbVal$t_leisure/60)
XPre = pred[,3:7]

round(sqrt(colMeans((XObs - XPre)^2)),2) 
round(sqrt(mean((colSums(XObs) - colSums(XPre))^2)),2) 

# ----------------------------------------------------------------- #
#---- switch off writing to file                                 ----
# ----------------------------------------------------------------- #

apollo_sink()

